package com.jzo2o.foundations.handler;

import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.service.HomeService;
import com.jzo2o.foundations.service.IRegionService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class SpringCacheSyncHandler {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IRegionService regionService;

    @Resource
    private HomeService homeService;

    //定时更新能缓存
    @XxlJob("activeRegionCacheSync")//指定任务名称
    public void activeRegionCacheSync() {

        log.info(">>>>>>>开始进行缓存同步 更新已经启用的区域");

        //先删除旧的缓存
        //获取key
        String key = RedisConstants.CacheName.JZ_CACHE+"::ACTIVE_REGION:";
        //调用delete方法删除缓存
        redisTemplate.delete(key);

        //添加缓存 直接查询最新数据 实现添加缓存
        List<RegionSimpleResDTO> regionSimpleResDTOS = regionService.queryActiveRegionListCache();

        //遍历列表 对每个区域的服务进行缓存删除 和 更新
        regionSimpleResDTOS.forEach(item ->{
            String key1 = RedisConstants.CacheName.SERVE_ICON +"::"+item.getId();
            //先删除缓存
            redisTemplate.delete(key1);

            //调用查询方法更新缓存
            homeService.queryServeIconCategoryByRegionIdCache(item.getId());

        });

        log.info(">>>>>>>>>更新已启用的区域完成");
    }
}
